package org.eclipse.php.internal.console.ui.view;


import java.util.Observable;
import java.util.Observer;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.php.internal.console.ui.editor.ConsoleEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class HistoryView extends ViewPart implements Observer, ISelectionChangedListener {
	public static final String ID = "org.eclipse.php.console.views.HistoryView";
	private TableViewer viewer;
	private Action action1;
	private Action action2;
	private Action doubleClickAction;
	private HistoryListModel listModel; 
	private ISelectionListener pageSelectionListener;
	private StyledText text;
	
	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	 
	class HistoryViewContentProvider implements IStructuredContentProvider {

		public Object[] getElements(Object inputElement) {
			HistoryListModel listModel = (HistoryListModel) inputElement;
			return listModel.toArray();
		}

		public void dispose() {
		}

		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			
		}

	}
	class HistoryViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}

		public String getColumnText(Object element, int columnIndex) {
			Object[] obj = (Object[])element;
			return (String)obj[columnIndex];
		}
	}

	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public HistoryView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		SashForm sf = new SashForm(parent, SWT.HORIZONTAL);
		
		TableLayout layout = new TableLayout();
		layout.addColumnData(new ColumnWeightData(4, 20, true));
		layout.addColumnData(new ColumnWeightData(30, 30, true));
		layout.addColumnData(new ColumnWeightData(60, 60, true));
		Table table = new Table(sf, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL);
		this.viewer = new TableViewer(table);
		this.viewer.setContentProvider(new HistoryViewContentProvider());
		this.viewer.setLabelProvider(new HistoryViewLabelProvider());
		ISelection sel = getSite().getPage().getSelection();
		if (sel != null && sel instanceof ConsoleEditor) {
			HistoryListModel listModel2 = ((ConsoleEditor)sel).getHistoryListModel();
			viewer.setInput(listModel2);
			listModel2.deleteObservers();
			listModel2.addObserver(this);
		} else {
			viewer.setInput(listModel);
			if (listModel != null) listModel.deleteObservers();
			if (listModel != null) listModel.addObserver(this);
		}
		table.setLayout(layout);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		TableColumn column1 = new TableColumn(table, SWT.LEFT);
		column1.setText("#");
		TableColumn column2 = new TableColumn(table, SWT.LEFT);
		column2.setText("Date/Time");
		TableColumn column3 = new TableColumn(table, SWT.LEFT);
		column3.setText("Command");
		viewer.addSelectionChangedListener(this);
		this.text = new StyledText(sf, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		text.setText("");
		hookPageSelection();
		
//		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
//		viewer.setContentProvider(new ViewContentProvider());
//		viewer.setLabelProvider(new ViewLabelProvider());
//		viewer.setSorter(new NameSorter());
//		viewer.setInput(getViewSite());
//		makeActions();
//		hookContextMenu();
//		hookDoubleClickAction();
//		contributeToActionBars();
	}

	private void hookPageSelection() {
		pageSelectionListener = new ISelectionListener() {
				public void selectionChanged(IWorkbenchPart part, ISelection selection) {
					pageSelectionChanged(part, selection);
				}
			};
		getSite().getPage().addPostSelectionListener(pageSelectionListener);
	}
	
	protected void pageSelectionChanged(IWorkbenchPart part, ISelection selection) {
		if (part == this)
			return;
		if (part instanceof ConsoleEditor) {
			this.listModel = ((ConsoleEditor)part).getHistoryListModel();
			this.listModel.deleteObservers();
			this.listModel.addObserver(this);
			this.viewer.setInput(this.listModel);
//			this.text.setText("");
		}	
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				HistoryView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		action2 = new Action() {
			public void run() {
				showMessage("Action 2 executed");
			}
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				showMessage("Double-click detected on "+obj.toString());
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"History",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
//		viewer.getControl().setFocus();
	}

	public void update(Observable arg0, Object arg1) {
		this.viewer.setInput(arg1);
	}

	public void selectionChanged(SelectionChangedEvent event) {
		StructuredSelection sel = (StructuredSelection) event.getSelection();
		if (sel.isEmpty()) return;
		Object obj = sel.getFirstElement();
		Object[] rtn = (Object[])obj;
		this.text.setText((String)rtn[2]);
	}
	
	public void clearHistory() {
		this.listModel.clearHistoryListModel();
	}
}